package httpService

import (
	"github.com/labstack/echo/v4"
	"gorm.io/gorm"
	"pm/db"
	"pm/model"
)

func UserChangePasswd(c echo.Context)error{
	password := c.FormValue("password")
	oldPasswd := c.FormValue("old_password")
	repeatPassword := c.FormValue("repeat_password")
	if repeatPassword != password{
		return c.JSON(200, map[string]interface{}{
			"status": 1,
			"msg":"密码重复错误",
		})
	}
	loginUser := c.Get("login_user").(string)
	var userInfo model.User
	err := db.NewDb().Model(&model.User{}).Where("username = ?", loginUser).Take(&userInfo).Error
	if err != nil && err == gorm.ErrRecordNotFound{
		if loginUser == DefaultUserName && oldPasswd == DefaultPassword{
			userInfo.Username = loginUser
			userInfo.Password = password
			if err := db.NewDb().Model(&model.User{}).Create(&userInfo).Error;err != nil{

				return c.JSON(200, map[string]interface{}{
					"status": 3,
					"msg":"系统错误2",
				})
			}else{
				return c.JSON(200, map[string]interface{}{
					"status": 0,
					"msg":"",
				})
			}
		}
	}
	if err != nil{
		return c.JSON(200, map[string]interface{}{
			"status": 2,
			"msg":"系统错误1",
		})
	}
	userInfo.Password = password
	if err := db.NewDb().Model(&model.User{}).Where("ID=?", userInfo.ID).Updates(&userInfo).Error;err != nil{
		return c.JSON(200, map[string]interface{}{
			"status": 4,
			"msg":"系统错误3",
		})
	}
	return c.JSON(200, map[string]interface{}{
		"status": 0,
		"msg":"",
	})
}
